package com.southwind.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.common.Cache;
import com.southwind.common.ResultObj;
import com.southwind.entity.SysUser;
import com.southwind.form.LoginForm;
import com.southwind.service.SysUserService;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedirectController {

    @Autowired
    private SysUserService userService;

    @GetMapping("/getCode")
    public String getCode(){
        SpecCaptcha captcha = new SpecCaptcha(130, 48,4);
        String code = captcha.text().toLowerCase();
        Cache.set("code", code);
        return captcha.toBase64();
    }

    @GetMapping("/login")
    public ResultObj login(LoginForm loginForm){
        //验证用户名
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loginname", loginForm.getLoginname());
        SysUser user = this.userService.getOne(queryWrapper);
        if(user == null) return ResultObj.LOGIN_LOGINNAME_ERROR;
        //验证密码
        String pwd = DigestUtils.md5DigestAsHex(loginForm.getPwd().getBytes());
        if(!pwd.equals(user.getPwd())) return ResultObj.LOGIN_PASSWORD_ERROR;
        //校验验证码
        String code = (String) Cache.get("code");
        if(!code.equals(loginForm.getCode())) return ResultObj.LOGIN_CODE_ERROR;
        Cache.set("user", user);
        ResultObj loginSuccess = ResultObj.LOGIN_SUCCESS;
        loginSuccess.setUser(user);
        return loginSuccess;
    }

}
